const Router = require('@koa/router');
const { Sight } = require('../databases');
const { Op } = require('sequelize');

const sightRouter = new Router({
    prefix: '/sight'
});

// 获取景点列表
sightRouter.get('/', async (ctx) => {
    try {
        const { page = 1, pageSize = 10, status, minRating, search, name } = ctx.query;
        const offset = (page - 1) * pageSize;
        
        // 查询条件
        const where = {};
        if (status) {
            where.status = status;
        }
        if (minRating) {
            where.rating = { [Op.gte]: parseFloat(minRating) };
        }
        // 模糊查询
        if (name) {
            where[Op.or] = [
                { name: { [Op.like]: `%${name}%` } },
                { description: { [Op.like]: `%${name}%` } }
            ];
        }

        const { count, rows } = await Sight.findAndCountAll({
            where,
            offset,
            limit: parseInt(pageSize),
            order: [['createdAt', 'DESC']]
        });

        ctx.body = {
            status: 'success',
            data: {
                total: count,
                items: rows,
                currentPage: parseInt(page),
                pageSize: parseInt(pageSize)
            }
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            status: 'error',
            message: error.message
        };
    }
});

// 获取单个景点详情
sightRouter.get('/:id', async (ctx) => {
    try {
        const sight = await Sight.findByPk(ctx.params.id);
        if (!sight) {
            ctx.status = 404;
            ctx.body = {
                status: 'error',
                message: '景点不存在'
            };
            return;
        }
        
        ctx.body = {
            status: 'success',
            data: sight
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            status: 'error',
            message: error.message
        };
    }
});

// 创建新景点
sightRouter.post('/', async (ctx) => {
    try {
        const sightData = ctx.request.body;
        
        // 验证必要字段
        const requiredFields = ['name', 'description', 'address'];
        for (const field of requiredFields) {
            if (!sightData[field]) {
                ctx.status = 400;
                ctx.body = {
                    status: 'error',
                    message: `缺少必要字段: ${field}`
                };
                return;
            }
        }

        const sight = await Sight.create(sightData);
        ctx.status = 201;
        ctx.body = {
            status: 'success',
            data: sight
        };
    } catch (error) {
        ctx.status = error.name === 'SequelizeUniqueConstraintError' ? 400 : 500;
        ctx.body = {
            status: 'error',
            message: error.name === 'SequelizeUniqueConstraintError' ? 
                '景点名称已存在' : error.message
        };
    }
});

// 更新景点信息（统一的更新接口）
sightRouter.put('/:id', async (ctx) => {
    try {
        const sight = await Sight.findByPk(ctx.params.id);
        if (!sight) {
            ctx.status = 404;
            ctx.body = {
                status: 'error',
                message: '景点不存在'
            };
            return;
        }

        const updates = ctx.request.body;
        
        // 验证状态值
        if (updates.status && !['open', 'closed', 'maintenance'].includes(updates.status)) {
            ctx.status = 400;
            ctx.body = {
                status: 'error',
                message: '无效的景点状态'
            };
            return;
        }

        // 验证图片数组
        if (updates.images && !Array.isArray(updates.images)) {
            ctx.status = 400;
            ctx.body = {
                status: 'error',
                message: '图片数据必须是数组格式'
            };
            return;
        }

        await sight.update(updates);
        
        ctx.body = {
            status: 'success',
            data: sight
        };
    } catch (error) {
        ctx.status = error.name === 'SequelizeUniqueConstraintError' ? 400 : 500;
        ctx.body = {
            status: 'error',
            message: error.name === 'SequelizeUniqueConstraintError' ? 
                '景点名称已存在' : error.message
        };
    }
});

// 删除景点
sightRouter.delete('/:id', async (ctx) => {
    try {
        const sight = await Sight.findByPk(ctx.params.id);
        if (!sight) {
            ctx.status = 404;
            ctx.body = {
                status: 'error',
                message: '景点不存在'
            };
            return;
        }

        await sight.destroy();
        ctx.body = {
            status: 'success',
            message: '景点已删除'
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            status: 'error',
            message: error.message
        };
    }
});

// 收藏景点
sightRouter.post('/:id/favorite', async (ctx) => {
    try {
        const sight = await Sight.findByPk(ctx.params.id);
        if (!sight) {
            ctx.status = 404;
            ctx.body = {
                status: 'error',
                message: '景点不存在'
            };
            return;
        }

        await sight.increment('favoriteCount');
        await sight.reload();
        
        ctx.body = {
            status: 'success',
            data: { favoriteCount: sight.favoriteCount }
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            status: 'error',
            message: error.message
        };
    }
});

// 取消收藏景点
sightRouter.delete('/:id/favorite', async (ctx) => {
    try {
        const sight = await Sight.findByPk(ctx.params.id);
        if (!sight) {
            ctx.status = 404;
            ctx.body = {
                status: 'error',
                message: '景点不存在'
            };
            return;
        }

        if (sight.favoriteCount > 0) {
            await sight.decrement('favoriteCount');
            await sight.reload();
        }
        
        ctx.body = {
            status: 'success',
            data: { favoriteCount: sight.favoriteCount }
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            status: 'error',
            message: error.message
        };
    }
});

//获取景点总数
sightRouter.get('/total/sights', async (ctx) => {
    try {
        const count = await Sight.count();
        ctx.body = {
            status: 'success',
            data: { count }
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            status: 'error',
            message: error.message
        };
    }
});

// 获取热门景点（基于评分和收藏数）
sightRouter.get('/hot/sight', async (ctx) => {
    try {
        // 获取参数，默认返回前5个热门景点
        const limit = parseInt(ctx.query.limit) || 5;
        
        // 使用现有的findTopRated方法获取高评分景点
        let hotSights = await Sight.findTopRated(limit);
        console.log('热门景点:', hotSights);
        
        // 格式化返回数据，包含前端需要的字段
        let formattedSights = hotSights.map(sight => ({
            id: sight.sightId,
            name: sight.name,
            favoriteCount: sight.favoriteCount,
            rating: sight.rating
        }));
        
        ctx.body = {
            status: 'success',
            data: formattedSights
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            status: 'error',
            message: error.message
        };
    }
});



module.exports = sightRouter;